package httpFunc

import (
	"bytes"
	"io/ioutil"
	"net/http"

	"github.com/gin-gonic/gin"
)

func Proxy(c *gin.Context, url string, token string) {
	body, err := ioutil.ReadAll(c.Request.Body)
	if err != nil {
		c.String(500, "Failed to create new request1: %v", err)
		return
	}
	req, err := http.NewRequest(c.Request.Method, "http://"+url, bytes.NewReader(body))
	if err != nil {
		// 这里处理错误，比如返回HTTP 500和错误信息
		c.String(500, "Failed to create new request: %v", err)
		return
	}
	// 将原请求的Header复制到新请求中
	for name, values := range c.Request.Header {
		for _, value := range values {
			req.Header.Add(name, value)
		}
	}
	// 添加token
	if req.Header.Get("token") == "" {
		req.Header.Add("token", token)
	} else {
		req.Header.Set("token", token)
	}

	// 发送请求到模块2
	resp, err := http.DefaultClient.Do(req)
	if err != nil {
		// 这里处理错误，比如返回HTTP 500和错误信息
		c.String(500, "Failed to do request: %v", err)
		return
	}

	// 将模块2的响应写回到原响应中
	defer resp.Body.Close()
	body, err = ioutil.ReadAll(resp.Body)
	if err != nil {
		c.String(500, "Failed to do request2: %v", err)
		return
	}
	c.Data(resp.StatusCode, resp.Header.Get("Content-Type"), body)
}
